<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
         <!--  <el-form-item>
            <el-input v-model="query.params.organId" placeholder="组织机构" />
          </el-form-item> -->
          <el-form-item>
            <el-input v-model="query.params.fitDevice" placeholder="适用机型" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.fileName" placeholder="文件名称" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.version" placeholder="软件版本" />
          </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'SOFTWARE_ADD'" type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="95">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="组织机构" width="110">
          <template slot-scope="scope">
            {{ scope.row.organId }}
          </template>
        </el-table-column>
        <el-table-column label="适用机型" width="110">
          <template slot-scope="scope">
            {{ scope.row.fitDevice }}
          </template>
        </el-table-column>
        <el-table-column label="下载地址" width="110">
          <template slot-scope="scope">
            {{ scope.row.downloadUrl }}
          </template>
        </el-table-column>
        <el-table-column label="文件名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.fileName }}
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="110">
          <template slot-scope="scope">{{scope.row.fileSize+"("+getFileSize(scope.row.fileSize)+")"}}</template>
        </el-table-column>
        <el-table-column label="文件Md5" width="110">
          <template slot-scope="scope">
            {{ scope.row.md5 }}
          </template>
        </el-table-column>
        <el-table-column label="软件版本" width="110">
          <template slot-scope="scope">
            {{ scope.row.version }}
          </template>
        </el-table-column>
        <el-table-column label="生成者" width="110">
          <template slot-scope="scope">
            {{ scope.row.createBy }}
          </template>
        </el-table-column>
        <el-table-column label="更新者" width="110">
          <template slot-scope="scope">
            {{ scope.row.updateBy }}
          </template>
        </el-table-column>
        <el-table-column label="生成日期" width="110">
          <template slot-scope="scope">
            {{ scope.row.createDate }}
          </template>
        </el-table-column>
        <el-table-column label="更新日期" width="110">
          <template slot-scope="scope">
            {{ scope.row.updateDate }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="created_at" label="操作" width="200">
          <template slot-scope="scope">
            <span class="el-tag el-tag--info el-tag--mini" v-has="'SOFTWARE_EDIT'"  style="cursor: pointer;" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </span>
            <span v-if="!scope.row.isSet" v-has="'SOFTWARE_DOWNLOAD'" class="el-tag el-tag--primary el-tag--mini" style="cursor: pointer;" @click="downloadFile(scope.row.downloadUrl)">
              下载
            </span>
            <span v-if="!scope.row.isSet" v-has="'SOFTWARE_UPGRADE'"  class="el-tag el-tag--success el-tag--mini" style="cursor: pointer;" @click="toUpgradeDevice(scope.row)">
              推送
            </span>
            <span v-if="!scope.row.isSet" v-has="'SOFTWARE_DEL'"  class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="bindForm" :rules="softwareRules">
          <el-form-item label="适用机型" prop="fitDevice">
            <el-input v-model="form.fitDevice" placeholder="适用机型" auto-complete="off" />
          </el-form-item>
          <el-form-item label="软件版本" prop="version">
            <el-input v-model="form.version" placeholder="软件版本" auto-complete="off" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="备注" auto-complete="off" />
          </el-form-item>
          <el-form-item label="选择文件">
            <el-upload class="upload-demo" ref="upload" action="http://127.0.0.1:8765/software.controller/Software/uploadFile" :on-success="uploadchange" :limit="1">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave('bindForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisibleDevice">
        <div class="filter-container">
          <div style="display:inline-block;font-size:15px;"></div>
          <el-input clearable @keyup.enter.native="handleFilter" v-model="devlistQuery.deviceCode" style="width: 200px;margin-right:15px;margin-top:7px" class="filter-item" placeholder="设备编码" />
          <div style="display:inline-block;font-size:15px;"></div>
          <el-input clearable @keyup.enter.native="handleFilter" v-model="devlistQuery.type" style="width: 200px;margin-right:20px;margin-top:7px" class="filter-item" placeholder="设备类型" />
          <div style="display:inline-block;font-size:15px;"></div>
          <el-button class="filter-item" type="primary" v-waves style="margin-top:8px;" icon="el-icon-search" @click="devHandleFilter">搜索</el-button>
        </div>
        <!-- table 表格 -->
        <el-table :data="devlist" v-loading="devlistLoading" row-key="index" element-loading-text="给我一点时间" border fit highlight-current-row height="350" ref="multipleTable" @select="selectDevTable" @select-all="selectDevAllTable" @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column label="序号" prop="index" align="center" type="selection" />
          <el-table-column label="设备编码" prop="deviceCode" align="center" />
          <el-table-column label="设备名称" prop="deviceName" align="center" />
          <el-table-column label="设备类型" prop="deviceTypeName" align="center" />
          <el-table-column label="所属组织" prop="organName" align="center" />
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" :loading="doUpgradeButton" @click="doUpgrade()">升级设备</el-button>
        </div>
        <!-- pagination 分页 -->
        <div class="pagination-container">
          <el-pagination background @size-change="devhandleSizeChange" @current-change="devhandleCurrentChange" :current-page="devCurrentPage" :page-sizes="[5,10,20, 30, 40,1000,9999]" :page-size="devPageSize" layout="total, sizes, prev, pager, next, jumper" :total="devtotal">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit, upgradeDevice, getDeviceList } from '@/api/Software/'
import { getOrganId, getOrganPath } from '@/api/utils'
export default {
  data() {
    return {
      doUpgradeButton: false,
      list: null,
      devlist: null,
      dev: {
        list: false,
        add: false,
        chart: false
      },
      devlistQuery: { params: {organPath: '',},},
      devtotal: 0,
      devArray: null,
      devCurrentPage: 1,
      devPageSize: 10,
      software: null,
      listLoading: true,
      devlistLoading: false,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogFormVisibleDevice: false,
      form: {
        id: '',
        organId: '',
        fitDevice: '',
        downloadUrl: '',
        fileName: '',
        fileSize: '',
        md5: '',
        version: '',
        releaseDate: '',
        ctime: '',
        createBy: '',
        updateBy: '',
        createDate: '',
        updateDate: '',
        remark: '',
        'id': ''
      },
      softwareRules: {
        fitDevice: [{ required: true, message: '请输入适用机型', trigger: 'blur' },

        ],
        version: [{ required: true, message: '请输入软件版本', trigger: 'blur' }, ]
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {},
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }],
        value: ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {

    //设备列表查找
    devHandleFilter() {
      this.devArray = null;
      this.dev.list = true;
      this.fetchDeviceData();
      this.dev.list = false
    },

    devhandleSizeChange(val) {
      this.devCurrentPage = 1
      this.devPageSize = val
      this.fetchDeviceData()

    },
    devhandleCurrentChange(val) {
      this.devCurrentPage = val
      this.fetchDeviceData()


    },

    //推送升级设备
    toUpgradeDevice(row) {
      this.software = row;
      this.dialogFormVisibleDevice = true;
      this.doUpgradeButton=false;
    },

    //升级设备
    doUpgrade() {
      if (this.devArray == null || this.devArray.length == 0) {
        this.$message({
          type: 'warning',
          message: `请选择设备!`
        })
      } else {


        this.$confirm('是否确定升级?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.doUpgradeButton=true;
          upgradeDevice({
            deviceList: JSON.stringify(this.devArray),
            softwareId: this.software.id,
            version: this.software.version,
          }).then(response => {
            const data = response.data
            console.log(data)
            if (data.status == 1) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData();
               this.dialogFormVisibleDevice=false;
            } else if (data.status == 403) {
              this.$message({
                type: 'warning',
                message: data.description
              })
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消升级'
          })
        })

      }

    },
    //保存选中记录
    selectDevTable(selection, row) {
      this.devArray = selection;
    },
    //保存所有选中记录
    selectDevAllTable(selection) {
      this.devArray = selection;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //下载
    downloadFile(downloadUrl) {
      var url = "http://127.0.0.1:8765/software.controller/Software/downloadFile?filePath=" + downloadUrl;
      window.open(url, '_blank');
    },
    //格式化文件大小
    getFileSize(size) {
      if (!size)
        return "";

      var num = 1024.00; //byte

      if (size < num)
        return size + "B";
      if (size < Math.pow(num, 2))
        return (size / num).toFixed(2) + "K"; //kb
      if (size < Math.pow(num, 3))
        return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
      if (size < Math.pow(num, 4))
        return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
      return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
    },
    //文件上传返回
    uploadchange(response, file, fileList) {
      console.log(response);
      //上传成功
      if (response.status == 50001) {
        this.form.fileName = response.data.fileName;
        this.form.fileSize = response.data.fileSize;
        this.form.downloadUrl = response.data.downloadUrl;

      } else {
        this.$message({
          type: 'success',
          message: `上传出错!`
        })
      }
    },
    fetchData() {
      this.listLoading = true
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    fetchDeviceData() {
         if (!this.devlistQuery.params.organPath) {
        this.devlistQuery.params.organPath = getOrganPath()
      }
      this.devlistLoading = true
      getDeviceList(this.devlistQuery, this.devCurrentPage, this.devPageSize).then(response => {
        const data = response.data
        this.devtotal = data.totalCount
        this.devPageSize = data.pageSize
        this.devCurrentPage = data.currentPage
        this.devlist = data.entities
        this.devlistLoading = false
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData();
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.organId = getOrganId();
      this.form.fitDevice = ''
      this.form.downloadUrl = ''
      this.form.fileName = ''
      this.form.fileSize = ''
      this.form.md5 = ''
      this.form.version = ''
      this.form.releaseDate = ''
      this.form.ctime = ''
      this.form.createBy = ''
      this.form.updateBy = ''
      this.form.createDate = ''
      this.form.updateDate = ''
      this.form.remark = ''
      this.addForVisible = false
      //清空文件上传的列表
      this.$refs.upload.clearFiles();
      this.$refs['bindForm'].resetFi
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)
      this.form.id = row.id
      this.form.organId = row.organId
      this.form.fitDevice = row.fitDevice
      this.form.downloadUrl = row.downloadUrl
      this.form.fileName = row.fileName
      this.form.fileSize = row.fileSize
      this.form.md5 = row.md5
      this.form.version = row.version
      this.form.releaseDate = row.releaseDate
      this.form.ctime = row.ctime
      this.form.createBy = row.createBy
      this.form.updateBy = row.updateBy
      this.form.createDate = row.createDate
      this.form.updateDate = row.updateDate
      this.form.remark = row.remark
      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status == 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          doEdit(this.form).then(response => {
            debugger
            console.log(response)
            const data = response.data
            if (data.status) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData();
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }

      })

    },
    handleEditSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {

          doEdit(this.form).then(response => {
            debugger
            console.log(response)
            const data = response.data
            if (data.status) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.fetchData();
            } else {
              this.$message({
                type: 'info',
                message: '操作失败!'
              })
            }
            this.listLoading = false
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }

      })

    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}

</script>
